from django.conf import settings
from django.core.mail import send_mail
from django_redis import get_redis_connection
from rest_framework import serializers

from celery_tasks.sms.task import send_email
from users.models import User
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS


class UserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(write_only=True, min_length=8, max_length=20)
    sms_code = serializers.CharField(write_only=True, min_length=6, max_length=6)
    allow = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ['allow', 'mobile', 'password',
                  'password2', 'sms_code', 'username', 'id', 'token']

        extra_kwargs = {
            'username': {
                'min_length': 6,
                'max_length': 20,
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20
            }
        }

    def validate_allow(self, value):
        # 检查是否同意协议
        if value != 'true':
            raise serializers.ValidationError('用户没有同意协议')
        return value

    def validate(self, attrs):
        # 密码一致
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 检查验证码
        conn = get_redis_connection('sms_session')
        rel_sms_code = conn.get('mobile_%s' % attrs['mobile'])
        if not rel_sms_code:
            raise serializers.ValidationError('验证码已过期')
        if attrs['sms_code'] != rel_sms_code.decode():
            raise serializers.ValidationError('验证码输入错误')

        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']

        user = User.objects.create_user(**validated_data)

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)  # 载荷
        token = jwt_encode_handler(payload)  # token

        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User

        exclude = ('password',)


class UserUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email',)

    def update(self, instance, validated_data):
        instance.email = validated_data['email']
        instance.save()

        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps({'name': instance.username}).decode()

        subject = '沙雕点进来啊'
        verify_url = 'www.meiduo.site:8080/success_verify_email.html?token=' + token
        html_massage = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % ([validated_data['email']], verify_url, verify_url)

        send_email.delay(validated_data, html_massage)
        return instance
